package com.yunji.framework_template.common.util;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

/**
 * @author panguixiang
 */
public class CommonUtil {

    private static final Logger logger = Logger.getLogger(CommonUtil.class);

    /**
     * 获取指定日期的指定前几天
     * 
     * @param date
     * @param num
     * @return
     */
    public static Date getSpecifiedDayBefore(Date date, int num) {
        // Date date2 = date;
        Date date2 = new Date(date.getTime());
        long myTime = 0;
        // if (num == 1) {
        myTime = (date2.getTime() / 1000) - 60 * 60 * 24 * num;
        // } else {
        // myTime = (date2.getTime() / 1000) - 60 * 60 * 24 * (num + 1);
        // }
        date2.setTime(myTime * 1000);
        return date2;
    }

    /**
     * 比较两个日期字符串的大小
     * 
     * @param beginMonth 开始月 格式yyyy-mm
     * @param endMonth 结束月 格式yyyy_mm
     * @return 如果beginMonth>=endMonth、返回true
     */
    public static boolean checkMonth(String beginMonth, String endMonth) {
        boolean flag = false;
        if (beginMonth == null || endMonth == null) {
            throw new RuntimeException("The params beginMonth and endMonth should not be null.");
        }
        Date beginDate = CommonUtil.parseStrToDate(beginMonth + "-01");
        Date tempDate = CommonUtil.parseStrToDate(endMonth.replace("_", "-") + "-01");
        if (beginDate != null && tempDate != null && !tempDate.before(beginDate)) {
            flag = true;
        }
        return flag;
    }

    /**
     * 判断一个日期是否在两个日期之间
     * 
     * @param beginMonth
     * @param tmpMonth
     * @param endMonth
     * @return
     */
    public static boolean checkMonth(String beginMonth, String tmpMonth, String endMonth) {
        boolean flag = false;
        if (beginMonth == null || endMonth == null) {
            throw new RuntimeException("The params beginMonth and endMonth should not be null.");
        }
        Date beginDate = CommonUtil.parseStrToDate(beginMonth + "-01");
        Date tempDate = CommonUtil.parseStrToDate(tmpMonth.replace("_", "-") + "-01");

        // 获取指定year和month的第一天和最后一天
        int index = endMonth.indexOf("-");
        int year = Integer.parseInt(endMonth.substring(0, index));
        int month = Integer.parseInt(endMonth.substring(index + 1, endMonth.length()));
        Map<String, String> times = CommonUtil.getFirstLastDaysByMonth(year, month);
        String end = times.get("lastDate");
        Date endDate = CommonUtil.parseStrToDate(end);
        if (beginDate != null && tempDate != null && !tempDate.before(beginDate) && !tempDate.after(endDate)) {
            flag = true;
        }
        return flag;
    }

    /**
     * 获取到指定月份的第一天和最后一天
     * 
     * @param year
     * @param month
     * @return
     */
    public static TreeMap<String, String> getFirstLastDaysByMonth(int year, int month) {
        TreeMap<String, String> result = new TreeMap<String, String>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, year);
        cal.set(Calendar.MONTH, month);
        cal.set(Calendar.DAY_OF_MONTH, 1);
        cal.add(Calendar.DAY_OF_MONTH, -1);
        Date lastDate = cal.getTime();
        cal.set(Calendar.DAY_OF_MONTH, 1);
        Date firstDate = cal.getTime();
        result.put("firstDate", sdf.format(firstDate));
        result.put("lastDate", sdf.format(lastDate));
        return result;
    }

    /**
     * 将字符串转换为Date类型
     * 
     * @param date
     * @return
     */
    public static Date parseStrToDate(String date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            return sdf.parse(date);
        } catch (ParseException e) {
            logger.error("将字符串转换为Date类型异常", e);
        }
        return null;
    }

    public static String upload(String url, String filePath) throws IOException {

        File file = new File(filePath);
        if (!file.exists() || !file.isFile()) {
            return "";
        }

        /**
         * 第一部分
         */
        URL urlObj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();

        /**
         * 设置关键值
         */
        con.setRequestMethod("POST"); // 以Post方式提交表单，默认get方式
        con.setDoInput(true);
        con.setDoOutput(true);
        con.setUseCaches(false); // post方式不能使用缓存

        // 设置请求头信息
        con.setRequestProperty("Connection", "Keep-Alive");
        con.setRequestProperty("Charset", "UTF-8");

        // 设置边界
        String BOUNDARY = "----------" + System.currentTimeMillis();
        con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

        // 请求正文信息

        // 第一部分：
        StringBuilder sb = new StringBuilder();
        sb.append("--"); // ////////必须多两道线
        sb.append(BOUNDARY);
        sb.append("\r\n");
        sb.append("Content-Disposition: form-data;name=\"file\";filename=\"" + file.getName() + "\"\r\n");
        sb.append("Content-Type:application/octet-stream\r\n\r\n");

        byte[] head = sb.toString().getBytes("utf-8");

        // 获得输出流

        OutputStream out = null;
        // 文件正文部分
        DataInputStream in = null;
        try {
            out = new DataOutputStream(con.getOutputStream());
            out.write(head);
            in = new DataInputStream(new FileInputStream(file));
            int bytes = 0;
            byte[] bufferOut = new byte[1024];
            while ((bytes = in.read(bufferOut)) != -1) {
                out.write(bufferOut, 0, bytes);
            }
            in.close();

            // 结尾部分
            byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线

            out.write(foot);

            out.flush();
            out.close();

            /**
             * 读取服务器响应，必须读取,否则提交不成功
             */
            StringBuffer sbf = new StringBuffer();
            if (con.getResponseCode() == 200) {
                try {
                    // 定义BufferedReader输入流来读取URL的响应
                    BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
                    String line = null;

                    while ((line = reader.readLine()) != null) {
                        sbf.append(line);
                    }
                } catch (Exception e) {
                    logger.error("上传出现异常：" + filePath, e);
                }
            }

            return sbf.toString();
        } finally {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
        }

    }

    public static String create32UUID() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    public static String createItemId(String cate1) {
        return cate1.concat("_").concat(create32UUID());
    }

    public static String[] subStringUtil(String str, String subExt) throws Exception {
        String[] arr = new String[2];
        StringBuffer buffer = new StringBuffer(str);
        arr[0] = buffer.substring(0, str.lastIndexOf(subExt));
        arr[1] = buffer.substring(str.lastIndexOf(subExt) + 1, str.length());
        return arr;
    }

    /**
     * Date转化为pattern格式字符串
     * 
     * @param date
     * @return
     */
    public static String date2Str(Date date, String pattern) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
        return simpleDateFormat.format(date);
    }

    /**
     * 计算两个日期之间的日期集合
     * 
     * @param dBegin
     * @param dEnd
     * @return
     * @throws ParseException
     */
    public static List<Date> findDates(String start, String end) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date dBegin = sdf.parse(start);
        Date dEnd = sdf.parse(end);
        List<Date> lDate = new ArrayList<Date>();
        lDate.add(dBegin);
        Calendar calBegin = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的时间
        calBegin.setTime(dBegin);
        Calendar calEnd = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的时间
        calEnd.setTime(dEnd);
        // 测试此日期是否在指定日期之后
        while (dEnd.after(calBegin.getTime())) {
            // 根据日历的规则，为给定的日历字段添加或减去指定的时间量
            calBegin.add(Calendar.DAY_OF_MONTH, 1);
            lDate.add(calBegin.getTime());
        }
        // lDate.remove(0);//移除收尾两个日期
        // if(lDate.size()>0) {
        // lDate.remove(lDate.size()-1);
        // }
        return lDate;
    }

    /**
     * @param inSalePool cp内计费池
     * @param saleID 输入的内计费代码
     * @return
     */
    public static boolean checkInSaleId(String inSalePool, String saleID) {
        /* 再截取出后3位，转为整形和CP中的inSalePool对比，大于后者则不合法 */
        String saleIdChil = (saleID.substring(4, saleID.length())).replaceAll("^(0+)", "");
        return Integer.parseInt(inSalePool) > Integer.parseInt(saleIdChil);
    }

    /**
     * 计算两个日期之间的月集合
     * 
     * @param dBegin
     * @param dEnd
     * @return
     * @throws ParseException
     */
    public static Map<String, String> findMonths(String start, String end) throws ParseException {
        List<Date> list = findDates(start, end);
        Map<String, String> montMap = new HashMap<String, String>();
        String montStr = "";
        for (Date date : list) {
            montStr = date2Str(date, "yyyy_MM");
            if (!montMap.containsKey(montStr)) {
                montMap.put(montStr, montStr);
            }
        }
        return montMap;
    }

    /**
     * 获得指定长度的整形字符串，不足长度的前面以0补齐
     * 
     * @param length
     * @param number
     * @return
     */
    public static String lpad(int length, int number) {
        String f = "%0" + length + "d";
        return String.format(f, number);
    }

    /**
     * 根据itemId规则及cateGory2规则获得search类别分表名称
     * 
     * @param itemId
     * @param cateGory2
     * @return
     */
    public static String searchTableName(String itemId, String cateGory2) {
        if (StringUtils.isBlank(itemId) || StringUtils.isBlank(cateGory2)) {
            return "";
        }
        itemId = itemId.trim();
        char type = itemId.charAt(0);
        String tableNames = "";
        if (type == 's') {
            tableNames = "item_soft,search_soft";
        } else if (type == 'v') {
            tableNames = "item_video,search_video";
        } else if (type == 'd') {
            tableNames = "item_music,search_".concat(cateGory2.trim().toLowerCase());
        }
        return tableNames;
    }

    public static void main(String args[]) throws Exception {
        System.out.print(checkInSaleId("001", "0001001"));
        /*
         * List<Date> list = findDates("2014-06-11","2014-07-10"); Map<String,String> montMap = new
         * HashMap<String,String>(); String montStr = ""; for(Date date: list) {
         * System.out.println(date2Str(date,"yyyy_MM_dd")); montStr = date2Str(date,"yyyy_MM");
         * if(!montMap.containsKey(montStr)) { montMap.put(montStr,montStr); } } Iterator i =
         * montMap.keySet().iterator(); while(i.hasNext()) { System.out.println("month=="+i.next()); }
         */
        /*
         * String[] arr = subStringUtil("E:/program/dsdsf.jpg","."); System.out.println(arr[0]+"  "+arr[1]);
         */
    }

}
